import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
  HttpStatus,
  Logger,
} from '@nestjs/common';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();

    //获取出错的responese
    const exceptionRes = exception.getResponse();

    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;
    // 看下是否系统出错，如果出错返回500，设置返回的状态码、请求头、发送错误信息

    if (status === 500) {
      //控制台打印
      Logger.log('错误提示', {
        ...exception.getResponse(),
        url: request.originalUrl, // 错误的url地址
        timeStamp: new Date().toISOString(),
      });
    }

    const errorResponse = {
      error: exceptionRes.error,
      message:
        exceptionRes.message instanceof Array
          ? exceptionRes.message[0]
          : exceptionRes.message, //校验多层逻辑取第一个
      code: status, //返回原来的code状态码
      url: request.originalUrl, // 错误的url地址
      timeStamp: new Date().toISOString(),
    };

    response.status(status === 500 ? 500 : 200);
    response.header('Content-Type', 'application/json; charset=utf-8');
    response.send(errorResponse);

    /*
    let code;
    if (!exception.getStatus) {
      code = 500;
      return response.status(code).json({
        code,
        path: request.url,
        msg: exception.message,
        timeStamp: new Date().toISOString(),
      });
    } else {
      code = exception.getStatus();
    }


    const exceptionRes: any = exception.getResponse();
    const {
      error,
      message: msg,
    } = exceptionRes;
    console.log(exception.getResponse());

    response.status(code).json({
      code,
      path: request.url,
      error,
      msg,
      timeStamp: new Date().toISOString(),
    });

*/
  }
}
